package tech.cn.note.word.fun;

import java.time.LocalDate;

import com.deepoove.poi.render.compute.RenderDataCompute;
import lombok.extern.slf4j.Slf4j;
import tech.cn.note.utils.DateTimeUtils;

import org.springframework.stereotype.Service;

import static org.springframework.util.ObjectUtils.isEmpty;

@Service
@Slf4j
public class DaysBetween implements RenderFunction {
    /**
     * @param fields            参数1 开始日期 参数2 结束日期 参数3 可选，addDay 加上天数
     * @param renderDataCompute
     * @return
     */
    @Override
    public String doCalculate(String[] fields, RenderDataCompute renderDataCompute) {
        if (isEmpty(fields) || fields.length < 2) {
            return "";
        }

        if (fields.length == 2) {
            return String.valueOf(cal(fields, renderDataCompute));
        } else if (fields.length == 3) {
            Integer cal = this.cal(fields, renderDataCompute);
            String addDay = fields[2];
            return String.valueOf(cal + Integer.parseInt(addDay));
        }
        return "";
    }

    private Integer cal(String[] fields, RenderDataCompute renderDataCompute) {
        String para1 = fields[0];
        String para2 = fields[1];
        Object o1 = cal(renderDataCompute, para1);
        Object o2 = cal(renderDataCompute, para2);
        LocalDate startDateInclusive = DateTimeUtils.toLocalDate(o1);
        LocalDate endDateExclusive = DateTimeUtils.toLocalDate(o2);
        return (int) Math.abs(startDateInclusive.toEpochDay() - endDateExclusive.toEpochDay());
    }

    protected Object cal(RenderDataCompute renderDataCompute, String para) {
        Object o1 = renderDataCompute.compute(para);
        if (o1 == null) {
            throw new RuntimeException(String.format("无法计算[%s]的值", para));
        }
        return o1;
    }
}
